package com.ruoyi.web.controller.walmart;

import cn.hutool.core.util.IdUtil;
import cn.hutool.http.*;
import com.ruoyi.common.constant.WalmartConstant;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.walmart.domain.auth.ShopAuth;
import com.ruoyi.walmart.http.WalmartRequest;
import com.ruoyi.walmart.util.walmartUtil;
import org.apache.commons.lang3.ObjectUtils;

import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.Base64;
import java.util.HashMap;
import java.util.Map;

import static com.ruoyi.walmart.util.walmartUtil.getHeaders;

public class WalmartWebhookRegistration {

    private static final String API_URL = "https://marketplace.walmartapis.com/v3/webhooks/subscriptions"; // 假设的沃尔玛Webhook注册API URL
    private static final String CLIENT_ID = "7c48b0e7-2cc0-4479-b03e-1b99721d2d20";
    private static final String CLIENT_SECRET = "IcGImByuue-O1PRHmypWAlIRwK2i5ZDZyxBrh8pmQc4XnGjvoJsAqjSUnCYDq9S8i0wNMRFhresHFXCXB3jRHw";

    public static void main(String[] args) {
        try {
            ShopAuth shopAuth = new ShopAuth();
            shopAuth.setClientId(CLIENT_ID);
            shopAuth.setClientSecret(CLIENT_SECRET);
            String request = request(API_URL, Method.POST,null,shopAuth);
            if(StringUtils.isEmpty(request)){
                return ;
            }
            System.out.println("request===="+request);
            /*// 获取Authorization头
            String authorization = walmartUtil.getAuthorization(CLIENT_ID, CLIENT_SECRET);
            // 1. 构建Webhook注册的请求体 (JSON格式)
            String jsonBody = "{"
                    + "\"url\": \"https://4177-113-87-225-167.ngrok-free.app/webhook\","
                    + "\"eventTypes\": ["
                    + "\"ORDER_STATUS_UPDATED\","
                    + "\"ORDER_SHIPPED\","
                    + "\"ORDER_CANCELLED\""
                    + "]"
                    + "}";

            // 2. 创建URL对象并打开连接
            URL url = new URL(API_URL);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();

            // 3. 设置请求方法为POST
            connection.setRequestMethod("POST");
            connection.setRequestProperty("Authorization", authorization);  // 设置Authorization头
            connection.setRequestProperty("Content-Type", "application/json");  // 设置Content-Type为JSON
            connection.setDoOutput(true);  // 允许输出请求体

            // 4. 发送请求体
            try (OutputStream os = connection.getOutputStream()) {
                byte[] input = jsonBody.getBytes(StandardCharsets.UTF_8);
                os.write(input, 0, input.length);
            }

            // 5. 获取并打印响应
            int responseCode = connection.getResponseCode();
            System.out.println("Response Code: " + responseCode);

            if (responseCode != 200) {
                // 打印错误信息
                try (BufferedReader in = new BufferedReader(new InputStreamReader(connection.getErrorStream(), StandardCharsets.UTF_8))) {
                    String inputLine;
                    StringBuilder errorResponse = new StringBuilder();
                    while ((inputLine = in.readLine()) != null) {
                        errorResponse.append(inputLine);
                    }
                    System.out.println("Error Response: " + errorResponse.toString());
                }
            } else {
                // 如果响应成功，打印响应体
                try (BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream(), StandardCharsets.UTF_8))) {
                    String inputLine;
                    StringBuilder response = new StringBuilder();
                    while ((inputLine = in.readLine()) != null) {
                        response.append(inputLine);
                    }
                    System.out.println("Response: " + response.toString());
                }
            }*/

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static String getAuthorization(String appKey, String appSecret) {
        // 拼接 clientId 和 clientSecret
        String str = appKey + ":" + appSecret;
        // 使用 java.util.Base64 进行 Base64 编码
        return "Basic " + Base64.getEncoder().encodeToString(str.getBytes(StandardCharsets.UTF_8));
    }
    public static String request(String requestUrl, Method method, Map<String, ?> paramMap, ShopAuth shopAuth) {

        HttpResponse response = null;
        try {
            if (Method.GET == method) {
                // get请求拼接参数
                if (paramMap != null && paramMap.size() > 0) {
                    if (requestUrl.indexOf("?") > 0) {
                        requestUrl = requestUrl + "&" + HttpUtil.toParams(paramMap);
                    } else {
                        requestUrl = requestUrl + "?" + HttpUtil.toParams(paramMap);
                    }
                }
            }
            String jsonBody = "{"
                    + "\"url\": \"https://4177-113-87-225-167.ngrok-free.app/webhook\","
                    + "\"eventTypes\": ["
                    + "\"ORDER_STATUS_UPDATED\","
                    + "\"ORDER_SHIPPED\","
                    + "\"ORDER_CANCELLED\""
                    + "]"
                    + "}";
            Map<String, String> headers = getHeaders( requestUrl, method, paramMap,shopAuth);
            HttpRequest httpRequest = HttpRequest
                    .of(requestUrl)
                    .setMethod(method)
                    .addHeaders(headers)
                    .contentType(ContentType.JSON.getValue())
                    .body(jsonBody);
            response = httpRequest.execute();
            if (HttpStatus.HTTP_OK == response.getStatus()) {
            }else {
                throw new ServiceException("调用Walmart API 错误: 状态码 " + response.getStatus());
            }
        }  catch (Exception e) {
            throw new ServiceException("调用Walmart API 异常: " + e.getMessage());
        } finally {
            if (ObjectUtils.isNotEmpty(response)){
                response.close();
            }
        }
        return requestUrl;
    }

    public static Map<String, String> getHeaders(String requestUrl,
                                                 Method method,
                                                 Map<String, ?> paramMap,ShopAuth shopAuth) {
        String authorization = getAuthorization(shopAuth.getClientId(), shopAuth.getClientSecret());
        Map<String, String> headers = new HashMap<>();
        headers.put("Authorization", authorization);
        headers.put("Accept","application/json");
        if(Method.POST == method){
            headers.put("Content-Type", "application/json");
        }
        return headers;
    }
}
